import { io } from 'socket.io-client';
import { showToast } from 'vant';

class WebSocketService {
  constructor() {
    this.socket = null;
    this.messageHandlers = new Set();
    this.globalMessageHandler = null;
  }

  // 初始化 WebSocket 连接
  init(userId) {
    userId = userId || localStorage.getItem('user_id');
    if (!userId) {
      // 未登录，静默返回
      return;
    }

    // 如果已经有连接，先断开
    if (this.socket) {
      console.log('断开现有连接...');
      this.socket.disconnect();
      this.socket = null;
    }

    console.log('正在连接WebSocket服务器...');
    console.log('当前用户ID:', userId);

    this.socket = io('http://1.14.98.17:7777', {
      cors: {
        origin: "*",
        methods: ["GET", "POST"]
      },
      timeout: 10000,
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });

    // 用户登录
    this.socket.emit('login', userId);
    console.log('已发送登录请求，用户ID:', userId);

    // 监听私聊消息
    this.socket.on('private_message', ({ from, message }) => {
      console.log('收到私聊消息:', { from, message });
      console.log('开始处理消息...');

      // 先处理全局消息存储
      console.log('调用 handleGlobalMessage...');
      this.handleGlobalMessage(from, message);

      // 然后通知所有注册的消息处理器
      console.log('通知消息处理器，当前处理器数量:', this.messageHandlers.size);
      console.log('消息处理器列表:', Array.from(this.messageHandlers));
      this.messageHandlers.forEach((handler, index) => {
        console.log(`调用第 ${index + 1} 个消息处理器:`, handler);
        try {
          handler({ from, message });
          console.log(`第 ${index + 1} 个消息处理器执行成功`);
        } catch (error) {
          console.error(`第 ${index + 1} 个消息处理器执行失败:`, error);
        }
      });
      console.log('消息处理完成');
    });

    // 连接成功
    this.socket.on('connect', () => {
      console.log('WebSocket连接成功，连接ID:', this.socket.id);
      console.log('重新发送登录请求...');
      this.socket.emit('login', userId);
      showToast('连接成功');
    });

    // 连接错误
    this.socket.on('connect_error', (error) => {
      console.error('WebSocket连接错误:', error);
      showToast('连接失败，请检查网络');
    });

    // 断开连接
    this.socket.on('disconnect', (reason) => {
      console.log('WebSocket连接断开，原因:', reason);
      if (reason === 'io server disconnect') {
        showToast('服务器断开连接');
      }
    });

    // 重连尝试
    this.socket.on('reconnect_attempt', (attemptNumber) => {
      console.log('尝试重连，第', attemptNumber, '次');
    });

    // 重连成功
    this.socket.on('reconnect', (attemptNumber) => {
      console.log('重连成功，尝试次数:', attemptNumber);
      // 重新发送登录请求
      this.socket.emit('login', userId);
    });
  }

  // 处理全局消息存储
  handleGlobalMessage(from, message) {
    console.log('=== handleGlobalMessage 函数被调用 ===');
    console.log('参数:', { from, message });

    try {
      const currentUserId = localStorage.getItem('user_id');
      console.log('开始处理全局消息存储:', { from, message, currentUserId });

      if (!currentUserId) {
        console.log('当前用户未登录，跳过全局消息存储');
        return;
      }

      // 获取现有的聊天记录
      const chatRecords = JSON.parse(localStorage.getItem('chatRecords') || '{}');
      console.log('现有聊天记录:', chatRecords);

      // 创建或更新聊天记录
      const chatKey = `${currentUserId}_${from}`;
      const existingRecord = chatRecords[chatKey] || {};
      console.log('聊天记录key:', chatKey, '现有记录:', existingRecord);

      // 获取发送者信息（如果本地没有，先使用默认值）
      let senderInfo = {
        userId: from,
        nickname: existingRecord.nickname || '未知用户',
        avatar_url: existingRecord.avatar_url || ''
      };

      // 如果本地没有发送者信息，尝试从API获取
      if (!existingRecord.nickname || !existingRecord.avatar_url) {
        console.log('本地没有发送者信息，尝试从API获取:', from);
        this.fetchUserInfo(from).then(userInfo => {
          if (userInfo) {
            console.log('获取到用户信息:', userInfo);
            chatRecords[chatKey] = {
              ...chatRecords[chatKey],
              nickname: userInfo.nickname,
              avatar_url: userInfo.avatar_url,
              lastMessage: message,
              lastMessageTime: new Date().toISOString(),
              unreadCount: (existingRecord.unreadCount || 0) + 1
            };
            localStorage.setItem('chatRecords', JSON.stringify(chatRecords));
            console.log('更新后的聊天记录:', chatRecords[chatKey]);
          }
        });
      } else {
        // 直接更新聊天记录
        console.log('直接更新聊天记录');
        chatRecords[chatKey] = {
          ...senderInfo,
          lastMessage: message,
          lastMessageTime: new Date().toISOString(),
          unreadCount: (existingRecord.unreadCount || 0) + 1
        };
        localStorage.setItem('chatRecords', JSON.stringify(chatRecords));
        console.log('更新后的聊天记录:', chatRecords[chatKey]);
      }

      // 同时更新本地消息历史
      this.updateLocalMessageHistory(currentUserId, from, message, false);

      console.log('全局消息存储完成:', chatRecords[chatKey]);
    } catch (error) {
      console.error('全局消息存储失败:', error);
    }

    console.log('=== handleGlobalMessage 函数执行完成 ===');
  }

  // 更新本地消息历史
  updateLocalMessageHistory(currentUserId, from, message, isOwnMessage = false) {
    try {
      console.log('更新本地消息历史:', { currentUserId, from, message, isOwnMessage });

      const messageKey = `messages_${currentUserId}_${from}`;
      const existingMessages = JSON.parse(localStorage.getItem(messageKey) || '[]');

      const newMessage = {
        from: isOwnMessage ? 'me' : 'other',
        message: message,
        timestamp: new Date().toISOString()
      };

      existingMessages.push(newMessage);
      localStorage.setItem(messageKey, JSON.stringify(existingMessages));

      console.log('本地消息历史更新完成，消息数量:', existingMessages.length);
    } catch (error) {
      console.error('更新本地消息历史失败:', error);
    }
  }

  // 获取用户信息
  async fetchUserInfo(userId) {
    try {
      const response = await fetch(`http://1.14.98.17:8765/api/users/${userId}`);
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          return {
            nickname: data.data.nickname || '未知用户',
            avatar_url: data.data.avatar_url || ''
          };
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
    return null;
  }

  // 发送消息
  sendMessage(to, message) {
    if (!this.socket || !this.socket.connected) {
      showToast('连接已断开，请刷新页面重试');
      return false;
    }

    this.socket.emit('private_message', {
      to,
      message
    });

    // 更新本地消息历史（发送的消息）
    const currentUserId = localStorage.getItem('user_id');
    if (currentUserId) {
      this.updateLocalMessageHistory(currentUserId, to, message, true);
    }

    return true;
  }

  // 注册消息处理器
  addMessageHandler(handler) {
    this.messageHandlers.add(handler);
    console.log('消息处理器已注册，当前处理器数量:', this.messageHandlers.size);
    console.log('当前连接状态:', this.getConnectionStatus());
  }

  // 移除消息处理器
  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler);
  }

  // 断开连接
  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
    }
  }

  // 检查连接状态
  isConnected() {
    return this.socket && this.socket.connected;
  }

  // 获取当前连接状态
  getConnectionStatus() {
    return {
      connected: this.isConnected(),
      socketId: this.socket ? this.socket.id : null,
      handlersCount: this.messageHandlers.size
    };
  }
}

// 创建单例实例
const websocketService = new WebSocketService();
export default websocketService; 